package com.zihuop.client

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import android.view.View
import android.widget.TextView
import com.zihuop.server.IOperationListener
import com.zihuop.server.IProcessInfo
import com.zihuop.server.Test

class MainActivity : AppCompatActivity() {
    private val TAG = MainActivity::class.java.simpleName
    private lateinit var text: TextView
    private lateinit var mProcessInfo: IProcessInfo

    private val operationListener: IOperationListener = object : IOperationListener.Stub() {

        override fun onOperation(test: Test?) {
            runOnUiThread { "运算结果:${test.toString()}".also { text.text = it } }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        text = findViewById(R.id.tv_bind_remote_service)
    }

    var mServiceConnection: ServiceConnection = object : ServiceConnection {
        override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
            Log.i(TAG, "RemoteService onServiceConnected")
            mProcessInfo = IProcessInfo.Stub.asInterface(iBinder)
            text.text = "远程服务绑定成功"
        }

        override fun onServiceDisconnected(componentName: ComponentName) {
            Log.i(TAG, "RemoteService onServiceDisconnected")
        }
    }

    fun bindRemoteService(view: View) {
        val intent = Intent()
        intent.action = "com.zihuop.server.aidlservice"
        intent.setPackage("com.zihuop.server")
        val result = bindService(intent, mServiceConnection, Context.BIND_AUTO_CREATE)
        Log.d(TAG, "bindRemoteService 结果：$result")
    }

    fun registerService(view: View) {
        mProcessInfo.registerListener(operationListener)
        runOnUiThread { text.text = "本地服务注册完成" }
    }

    fun unregisterService(view: View) {
        mProcessInfo.unregisterListener(operationListener)
        runOnUiThread { text.text = "本地服务注销完成" }
    }

    fun operationService(view: View) {
        try {
            Log.i(TAG, "aidl调用 " + mProcessInfo.operation(Test(89, "1212")))
        } catch (e: RemoteException) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(mServiceConnection)
    }
}